package cn.iocoder.yudao.module.iot.service.wx;

import cn.iocoder.yudao.module.iot.controller.app.user.vo.WxSessionInfo;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class WechatService {

//    @Value("${wechat.appid}")
    private String appId;

//    @Value("${wechat.secret}")
    private String secret;

    private final RestTemplate restTemplate = new RestTemplate();

    /**
     * 根据 code 获取 openid 和 session_key
     */
    public WxSessionInfo getSessionInfo(String code) {
        String url = String.format(
                "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                appId, secret, code);

        log.info("[WechatService] 请求微信接口: {}", url);

        String result = restTemplate.getForObject(url, String.class);
        log.info("[WechatService] 微信返回: {}", result);

        WxSessionInfo sessionInfo = JSON.parseObject(result, WxSessionInfo.class);

        // 基本校验：微信返回错误码
        if (sessionInfo.getErrcode() != null && sessionInfo.getErrcode() != 0) {
            log.error("[WechatService] 微信登录失败：{}", sessionInfo.getErrmsg());
            throw new RuntimeException("微信登录失败：" + sessionInfo.getErrmsg());
        }

        return sessionInfo;
    }
}
